package com.omkarpatil.learningjpa2.mapping.onetomany.fk;

import javax.persistence.EntityManager;

import com.omkarpatil.learningjpa2.util.EntityManagerFactoryFactory;

public class TestDriver {

	public static void main(String[] args) {
		EntityManager em1 = EntityManagerFactoryFactory.getEntityManagerFactory().createEntityManager();
		em1.getTransaction().begin();
		
		Department dept1 = new Department("Development");
		em1.persist(dept1);
		int departmentId = dept1.getId();
		
		Employee emp1 = new Employee("Mr. X");
		emp1.setDepartment(dept1);
		em1.persist(emp1);
		
		Employee emp2 = new Employee("Mr. Y");
		emp2.setDepartment(dept1);
		em1.persist(emp2);
				
		em1.getTransaction().commit();
		em1.close();
		
		EntityManager em2 = EntityManagerFactoryFactory.getEntityManagerFactory().createEntityManager();
		em2.getTransaction().begin();
		
		Department department = em2.find(Department.class, departmentId);
		System.out.println("##### Iterating over employees in Development Department ...");
		for(Employee em : department.getEmployees()) {
			System.out.printf("##### Name : %s\n", em.getName());
		}
		
		em2.getTransaction().commit();
		em2.close();
	}
}
